package com.fuqi.android.zhongcai.service;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;

import com.android.volley.Response;
import com.android.volley.error.VolleyError;
import com.fuqi.android.zhongcai.base.Constants;
import com.fuqi.android.zhongcai.base.request.api.PushImgApi;
import com.fuqi.android.zhongcai.base.request.result.PushResult;
import com.fuqi.android.zhongcai.base.view.widget.CustomProgress;
import com.fuqi.android.zhongcai.business.shuig.OrderDict;
import com.fuqi.android.zhongcai.business.shuig.request.api.OrderHandleApi;
import com.fuqi.android.zhongcai.business.shuig.request.result.OrderHandleResult;
import com.fuqi.android.zhongcai.business.shuig.view.widget.CJRow.ARResponse;
import com.fuqi.android.zhongcai.sql.CacheImg;
import com.fuqi.android.zhongcai.sql.dao.SQLDao;
import com.fuqi.android.zhongcai.utils.FileUtil;
import com.fuqi.android.zhongcai.utils.ImageUtils;
import com.fuqi.framework.network.code.HandleCode;
import com.fuqi.framework.network.http.RequestManager;
import com.fuqi.framework.utils.StringUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import static com.fuqi.framework.utils.StringUtil.getListString;

/**
 * Created by Bruce on 2016/11/14.
 */
public class ImageUploadService extends Service{
    private ArrayList<String> netPhotos = new ArrayList<>();
    private ARResponse response = new ARResponse();;

    CacheImg cacheImg;
    List<CacheImg> cacheImgs = new ArrayList<>();

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.e("ccqx","onStartCommand");
        cacheImgs = SQLDao.getInstance(ImageUploadService.this).selectCacheList();

        response = new ARResponse("{}", "data");
        if(cacheImgs != null && cacheImgs.size() > 0){
            cacheImg = cacheImgs.get(0);
            response.update("ORDER_ID",cacheImg.getOrdid());
            netPhotos.addAll(StringUtil.getList(cacheImg.getPath(),","));
            doUpload();
        }
        return super.onStartCommand(intent, flags, startId);
    }

    private void doPublish(){
        Log.e("ccqx","doPublish");
        if(response != null) {
            if(cacheImg.getOrdtype().equals(Constants.TYPE_SHUI_GUAN)){
                if(netPhotos.size() > 6) {
                    response.update("threeProtectFile", netPhotos.get(0));  // 三保海报
                    response.update("attentionFile", netPhotos.get(1)); // 温馨提示海报
                    response.update("detailListFile", netPhotos.get(2));  // 地暖	材料清单路径
                    response.update("serviceCardFile", netPhotos.get(3));  //服务卡
                    response.update("warrantyCardFile", netPhotos.get(4));  // 质保卡
                    response.update("pressProtectFile", netPhotos.get(5));  //保压图
                    response.update("ORDER_STATUS", OrderDict.StatusType.DDZT_AZWC);
                    if (netPhotos != null && netPhotos.size() > 0)
                        response.update("finishFiles", getListString(netPhotos.subList(6,netPhotos.size()))); // 施工完成图片路径，多个路径中间用逗号分隔
                    RequestManager.getInstance().call(new OrderHandleApi(
                            new OrderHandleApi.OrderHandleParams(response.getDataWithMap()), respSuccListener, errorListener));
                }
            }else if(cacheImg.getOrdtype().equals(Constants.TYPE_DI_NUAN)){
                if(netPhotos.size() > 3) {
                    response.update("finishConfirmFile", netPhotos.get(0));  //
                    response.update("warrantyCardFile", netPhotos.get(1));  // 质保卡
                    response.update("detailListFile", netPhotos.get(2));  //保压图
                    response.update("ORDER_STATUS", OrderDict.StatusType.DDZT_AZWC);
                    if (netPhotos != null && netPhotos.size() > 0)
                        response.update("finishFiles", StringUtil.getListString(netPhotos.subList(3,netPhotos.size()))); // 施工完成图片路径，多个路径中间用逗号分隔
                    RequestManager.getInstance().call(new OrderHandleApi(
                            new OrderHandleApi.OrderHandleParams(response.getDataWithMap()), respSuccListener, errorListener));
                }
            }

        }else{
//            response.update("ORDER_STATUS", OrderDict.StatusType.DDZT_AZWC);
            RequestManager.getInstance().call(new OrderHandleApi(
                    new OrderHandleApi.OrderHandleParams(response.getDataWithMap()), respSuccListener, errorListener));
        }
        Log.i("response : ", response.toString());
    }

    private void doUpload(){
        List<File> files = ImageUtils.makePaths2ImgFileList(netPhotos);
        netPhotos.clear();
        PushImgApi p = new PushImgApi(respWorkersListener, errorListener, "files", files, null);
        RequestManager.getInstance().call(p);
    }


    Response.Listener<OrderHandleResult> respSuccListener = new Response.Listener<OrderHandleResult>() {

        @Override
        public void onResponse(OrderHandleResult r) {
            CustomProgress.close();
            if (HandleCode.requestSuccess()) {
                SQLDao.getInstance(ImageUploadService.this).delCacheWithOrdid(cacheImg.getOrdid());
                cacheImgs.remove(cacheImg);
                netPhotos.clear();
                Log.e("ccqx","respSuccListener");
//                cacheImgs = SQLDao.getInstance(ImageUploadService.this).selectCacheList();
                if(cacheImgs != null && cacheImgs.size() > 0){
                    cacheImg = cacheImgs.get(0);
                    Log.e("ccqx","ordid:"+cacheImg.getOrdid());
                    response.update("ORDER_ID",cacheImg.getOrdid());
                    netPhotos.addAll(StringUtil.getList(cacheImg.getPath(),","));
                    doUpload();
                }

            } else {
            }
        }
    };

    Response.Listener<PushResult> respWorkersListener = new Response.Listener<PushResult>() {

        @Override
        public void onResponse(PushResult response) {
            CustomProgress.close();
            if (HandleCode.requestSuccess()) {
                FileUtil.clearDir(FileUtil.getTempFile());
                netPhotos.addAll(StringUtil.getList(response.getPath(),","));
//                if(netPhotos.size() == selectedPhotos.size()) {
                doPublish();
//                }
                Log.i("juner", "juner respListener response : " + response.getPath());
            } else {
            }
        }
    };

    Response.ErrorListener errorListener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            CustomProgress.close();
            Log.i("juner", "juner  error.getMessage(): " + error.getMessage());

        }
    };

    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

        }
    };

}
